import { getDictList } from '@/assets/api/dict'
import dayjs from 'dayjs'

const dictMap = reactive({})
const timeStamp = new Map()

export function useDictionary(types = []) {
  if (typeof types === 'string') {
    getDict(types)
  } else {
    types.forEach((type) => {
      getDict(type)
    })
  }

  function getDict(type) {
    if (!timeStamp.has(type) || timeStamp.get(type).diff(dayjs(), 'minute') > 30) {
      timeStamp.set(type, dayjs())
      getDictList(type).then((res) => {
        if (res.code === 200) {
          dictMap[type] = res.data
        }
      })
    }
  }

  function getListByType(type) {
    return JSON.parse(JSON.stringify(dictMap[type] || []))
  }

  function translate(type, code) {
    if (!code || !dictMap[type]) return null
    return dictMap[type].find((i) => i.dictValue === code.toString())?.dictLabel
  }

  function getCode(type, label) {
    if (!label || !dictMap[type]) return null
    return dictMap[type].find((i) => i.dictLabel === label)?.dictValue
  }

  return {
    dictMap: readonly(dictMap),
    dictList: readonly(Array.from(Object.values(dictMap))),
    getListByType,
    translate,
    getCode,
  }
}
